package tt.dz.egobus.servicemanager.core.interceptor;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import tt.dz.egobus.annotation.LogAuto;
import tt.dz.egobus.dubbo.interceptor.InterceptorHandler;
import tt.dz.egobus.i18n.I18NProperties;
import tt.dz.egobus.i18n.SingletonI18NProperties;

import java.lang.reflect.Method;

/**
 * @author Anson
 * @date 17-3-19
 * @name 日志调用者
 * @since 1.0.1
 */
public class LoggerInterceptorHandler implements InterceptorHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerInterceptorHandler.class);
    private static final I18NProperties i18NProperties = SingletonI18NProperties.SINGL_TON.properties();

    @Override
    public void interceptBefore(Object obj, Method method, Object[] args) throws Exception {

    }

    @Override
    public void interceptPost(Object obj, Method method, Object[] args, Object result) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n当前对象类class={" + obj.getClass() + "},调用方法method={" + method.getName() + "}");
        stringBuilder.append("-->{");
        stringBuilder.append(this.doAutoLog(method));
        stringBuilder.append("\n    参数:" + this.wrapJson(args, 400));
        stringBuilder.append("\n    结果:" + this.wrapJson(result, 400));
        stringBuilder.append("\n}");
        LOGGER.info(stringBuilder.toString());
        stringBuilder.setLength(0);
    }

    private String doAutoLog(Method method) {
        LogAuto logAuto = AnnotationUtils.findAnnotation(method, LogAuto.class);
        if (logAuto == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n    业务注解信息:");
        stringBuilder.append("  bizCode={" + logAuto.bizCode() + "},");
        stringBuilder.append("  bizName={" + i18NProperties.get(String.valueOf(logAuto.bizCode())).getMsg() + "},");
        stringBuilder.append("  bizType={" + logAuto.bizType().toString() + "},");
        stringBuilder.append("  bizDesc={ " + logAuto.bizDesc() + "} ");
        return stringBuilder.toString();
    }

    private String wrapJson(Object obj, int maxLength) {
        if (obj == null) {
            return "";
        }
        String json = JSON.toJSONString(obj);
        if (json == null) {
            return "";
        }
        if (json.length() > maxLength) {
            json = json.substring(0, maxLength - 1);
        }
        return json;
    }

}
